import datetime
import time


# 单位: 毫秒
def current_timestamp():
    t = time.time()
    return round(t * 1000)


def current_time_string(time_format='%Y-%m-%d %H:%M:%S'):
    return datetime.datetime.now().strftime(time_format)


# 单位: 毫秒
def timestamp_to_string(timestamp, string_format='%Y-%m-%d %H:%M:%S'):
    return time.strftime(string_format, time.localtime(timestamp / 1000))


def time_string_to_timestamp(time_str, string_format='%Y-%m-%d %H:%M:%S'):
    return round(time.mktime(time.strptime(time_str, string_format)) * 1000)


# 单位: 毫秒 年月日
def timestamp_to_string1(timestamp, string_format='%Y-%m-%d'):
    return time.strftime(string_format, time.localtime(timestamp / 1000))


def time_string_to_timestamp1(time_str, string_format='%Y-%m-%d'):
    return round(time.mktime(time.strptime(time_str, string_format)) * 1000)


def start_time_stamp():
    time_start = current_time_string('%Y-%m-%d')
    time_start = time_string_to_timestamp(time_start + ' 03:00:00')
    return time_start


def timestamp_range(time_str='20190201-20190201'):
    ss = time_str.split('-')
    if ss[0] == '':
        ss[0] = '19970101'
    if ss[1] == '':
        ss[1] = '29990101'
    t1 = ss[0] + ' 00:00:00'
    t2 = ss[1] + ' 23:59:59'
    t1 = time_string_to_timestamp(t1, '%Y%m%d %H:%M:%S')
    t2 = time_string_to_timestamp(t2, '%Y%m%d %H:%M:%S')
    return t1, t2


# 获取本月的时间范围 维修单汇总
def get_time_timestamp_rang():
    now = datetime.datetime.now()
    d2 = now + datetime.timedelta(0)
    date = "%02d%02d%02d" % (d2.year, d2.month, d2.day)
    date1 = "%02d-%02d-%02d" % (d2.year, d2.month, d2.day)
    time_str = date[:-2] + '01' + '-' + date
    ss = time_str.split('-')
    t1 = ss[0]
    t2 = ss[1]
    t1 = time_string_to_timestamp1(t1, '%Y%m%d')
    t2 = time_string_to_timestamp1(t2, '%Y%m%d')
    return t1, t2


pre_timestamp = 0


def print_time_duration():
    # 用于调试
    global pre_timestamp
    if pre_timestamp == 0:
        pre_timestamp = current_timestamp()
    cur = current_timestamp()
    print('当前时间', current_time_string(), '距上次时间相差', (cur - pre_timestamp) / 1000, '秒')
    pre_timestamp = current_timestamp()